﻿using System;
using System.Net;
using System.Net.Http;
using Looptribe.Moodlin8.Model.Api;
using Newtonsoft.Json;

namespace Looptribe.Moodlin8.Model.Response
{
    class MoodleJsonResponse<T> : JsonResponse, IResponse<T>
    {
        private readonly T _data;
        private readonly Status _status;
        private readonly string _error;

        public T Data
        {
            get { return _data; }
        }

        public Status Status
        {
            get { return _status; }
        }

        public String Error
        {
            get { return _error; }
        }

        internal MoodleJsonResponse(HttpResponseMessage message, string body)
        {
            try
            {
                _data = JsonConvert.DeserializeObject<T>(body, Settings);
            }
            catch (JsonSerializationException ex)
            {
                _error = ex.Message;
                _status = Status.Error;
            }
            switch (message.StatusCode)
            {
                case HttpStatusCode.OK:
                    _status = Status.Ok;
                    break;
                case HttpStatusCode.Unauthorized:
                    _status = Status.Unauthorized;
                    break;
                default:
                    _error = String.Format("HTTP error: ", message.StatusCode);
                    _status = Status.Error;
                    break;
            }
        }

        internal MoodleJsonResponse(Status status, T data)
        {
            _data = data;
            _status = status;
        }
    }
}
